package com.zkingsoft.actions.admin.lin;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zkingsoft.anotations.RemoveRequestToken;
import com.zkingsoft.anotations.SaveRequestToken;
import com.zkingsoft.authority.MatrixAdapter;
import com.zkingsoft.constance.SystemConstance;
import com.zkingsoft.constraint.BaseController;
import com.zkingsoft.exception.GlobleException;
import com.zkingsoft.model.lin.LinOrder;
import com.zkingsoft.model.sys.SysUsers;
import com.zkingsoft.pojo.AjaxResult;
import com.zkingsoft.pojo.PaginationVO;
import com.zkingsoft.services.lin.LinOrderDetailsService;
import com.zkingsoft.services.lin.LinOrderService;
import com.zkingsoft.services.sys.SysUsersService;
import com.zkingsoft.util.ExcelUtil;
import com.zkingsoft.util.ExcelUtil.ViewExcel;
import com.zkingsoft.util.WebUtil;

/**
 * This field was generated by Zking.software.Codegen.
 * 
 * @date 2017-05-08 15:14
 */
@Controller
@RequestMapping(value = "admin/linOrder")
public class LinOrderController extends BaseController {

	@Resource
	private LinOrderService linOrderService;
	
	@Resource
	private SysUsersService sysUsersService;

	@Resource
	private MatrixAdapter matrixAdapter;
	
	@Resource
	private LinOrderDetailsService linOrderDetailsService;
	
	Logger log=Logger.getLogger(getClass());

	// 记录编辑前的值Before_Edit_Value
	public static final String BEV = "LinOrder_BEV";

	public static final String fnCode = "LinOrder";
	public static final String search = fnCode + ":search";
	public static final String edit = fnCode + ":edit";
	public static final String del = fnCode + ":del";
	public static final String add = fnCode + ":add";

	/**
	 * 列表显示
	 */
	@RequestMapping(value = "/showList")
	public @ResponseBody AjaxResult showList(LinOrder linOrder, PaginationVO pageVo) {
		System.out.println("+++++++++"+linOrder.getHotelName());
		matrixAdapter.isBtnPermitted(search);
		String login_plat = String.valueOf(WebUtil.getSessionAttribute(SystemConstance.LOGIN_PLAT));
		if(SystemConstance.PLAT_HOTEL.equals(login_plat)) {
			SysUsers loginUser = matrixAdapter.getLoginUser();
			loginUser = sysUsersService.findById(loginUser.getSuId());
			
			if(loginUser.getSuDeptId() == null) {
				return new AjaxResult(AjaxResult.STATUS_OK, new ArrayList<>());
			}
			
			linOrder.setHotelId(loginUser.getSuDeptId());
		}
		
		if (pageVo == null) {
			pageVo = new PaginationVO();
		}
		pageVo.setOrder("DESC");
		pageVo.setSort("order_createtime");
		
		return showList(linOrderService, linOrder, pageVo);
	}

	/**
	 * 新增或者修改页面
	 */
	@RemoveRequestToken
	@RequestMapping(value = "/addOrModify")
	public @ResponseBody AjaxResult addOrModify(LinOrder linOrder) {
		if (linOrder.getOrderId() != null) {
			matrixAdapter.isBtnPermitted(edit);
			linOrder.setOrderId(((LinOrder) WebUtil.getSessionAttribute(BEV))
					.getOrderId());
//			AjaxResult result = modify(linOrderService,
//					WebUtil.getSessionAttribute(BEV), linOrder, "订单");
			int i = linOrderService.modifyOrder((LinOrder) WebUtil.getSessionAttribute(BEV), linOrder);
			
			WebUtil.removeSessionAttribute(BEV);
			if (i > 0) {
				return new AjaxResult(AjaxResult.STATUS_OK, null, "订单修改成功");
			} else {
				return new AjaxResult(AjaxResult.STATUS_ERR, null, "订单修改失败");
			}
			
		} else {
			matrixAdapter.isBtnPermitted(add);
			if(linOrder == null || linOrder.getLinOrderDetails() == null || linOrder.getLinOrderDetails().isEmpty()) {
				return new AjaxResult(AjaxResult.STATUS_ERR, null, "详细数量不能为空");
			}
			
			int i = linOrderService.createOrder(linOrder);
			if (i > 0) {
				return new AjaxResult(AjaxResult.STATUS_OK, null, "订单添加成功");
			} else {
				return new AjaxResult(AjaxResult.STATUS_ERR, null, "订单添加失败");
			}
		}
	}

	/**
	 * 进入修改界面
	 */
	@SaveRequestToken
	@RequestMapping(value = "/editForm")
	public String editForm(Long id) {
		matrixAdapter.isBtnPermitted(edit);
		LinOrder linOrder;
		if (id != null) {
			linOrder = linOrderService.findById(id);
			WebUtil.getRequest().setAttribute("obj", linOrder);
			WebUtil.setSessionAttribute(BEV, linOrder);
		}
		return "admin/lin/LinOrder-form";
	}
	
	/**
	 * 进入损耗录入界面
	 */
	@SaveRequestToken
	@RequestMapping(value = "/editLossForm")
	public String editLossForm(Long id) {
		matrixAdapter.isBtnPermitted("LinLoss:edit");
		LinOrder linOrder;
		if (id != null) {
			linOrder = linOrderService.findById(id);
			WebUtil.getRequest().setAttribute("obj", linOrder);
			WebUtil.setSessionAttribute(BEV, linOrder);
		}
		return "admin/lin/LinLoss-form";
	}

	/**
	 * 删除
	 */
	@RequestMapping(value = "/del")
	public @ResponseBody AjaxResult del(String keys) {
		matrixAdapter.isBtnPermitted(del);
		return remove(linOrderService, keys);
	}

	/**
	 * 记录损耗
	 */
	@RemoveRequestToken
	@RequestMapping(value = "/modifyLoss")
	public @ResponseBody AjaxResult modifyLoss(LinOrder linOrder) {
		if (linOrder.getOrderId() == null) {
			return new AjaxResult(AjaxResult.STATUS_ERR, "记录失败，订单错误");
		}
		matrixAdapter.isBtnPermitted("LinLoss:edit");
		linOrder.setOrderId(((LinOrder) WebUtil.getSessionAttribute(BEV)).getOrderId());
		
		int i = linOrderService.modifyLoss(linOrder);
		
		WebUtil.removeSessionAttribute(BEV);
		if (i > 0) {
			return new AjaxResult(AjaxResult.STATUS_OK, null, "损耗记录成功");
		} else {
			return new AjaxResult(AjaxResult.STATUS_ERR, null, "损耗记录失败");
		}
	}
	
	/**
	 * 进入详情界面
	 */
	@RequestMapping(value = "/getDetail")
	public String getDetail(Long id, String orderType) {
		matrixAdapter.isBtnPermitted(search);
		LinOrder linOrder;
		if (id != null) {
			linOrder = linOrderService.findById(id);
			WebUtil.getRequest().setAttribute("obj", linOrder);
		}
		if(StringUtils.isNotBlank(orderType)) {
			WebUtil.getRequest().setAttribute("orderType", orderType);
		}
		return "admin/lin/LinOrder-detail";
	}
	
	/**
	 * 进入损耗详情界面
	 */
	@RequestMapping(value = "/getLossDetail")
	public String getLossDetail(Long id) {
		matrixAdapter.isBtnPermitted(search);
		LinOrder linOrder;
		if (id != null) {
			linOrder = linOrderService.findById(id);
			WebUtil.getRequest().setAttribute("obj", linOrder);
		}
		return "admin/lin/LinLoss-detail";
	}
	
	/**
	 * 获取我的账单
	 */
	@RequestMapping(value = "/showMyBill")
	@ResponseBody
	public AjaxResult showMyBill(LinOrder linOrder, PaginationVO pageVo) {
		matrixAdapter.isBtnPermitted(search);
		
		SysUsers loginUser = matrixAdapter.getLoginUser();
		loginUser = sysUsersService.findById(loginUser.getSuId());
		
		if(loginUser.getRoleIds() != null && !"".equals(loginUser.getRoleIds())) {
			String plates = sysUsersService.findUserPlates(loginUser);
			if(StringUtils.isNotBlank(plates) && plates.indexOf(SystemConstance.PLAT_COMPANY) == -1 
					&& plates.indexOf(SystemConstance.PLAT_FACTORY) == -1 && plates.indexOf(SystemConstance.PLAT_HOTEL) > -1) {
				
				if(loginUser.getSuDeptId() == null) {
					return new AjaxResult(AjaxResult.STATUS_OK, new ArrayList<>());
				}
				linOrder.setHotelId(loginUser.getSuDeptId());
			}
		}
		if (pageVo == null) {
			pageVo = new PaginationVO();
		}
		pageVo.setOrder("DESC");
		pageVo.setSort("order_createtime");
		
		return showList(linOrderService, linOrder, pageVo);
	}
	
	/**
	 * 进入账单详情界面
	 */
	@RequestMapping(value = "/getBillDetail")
	public String getBillDetail(Long id, String type) {
		
		WebUtil.getRequest().setAttribute("type", type);
		
		LinOrder linOrder;
		if (id != null) {
			linOrder = linOrderService.findById(id);
			WebUtil.getRequest().setAttribute("obj", linOrder);
		}
		return "admin/lin/LinBill-detail";
	}
	
	/**
	 * 获取订单流水
	 */
	@RequestMapping(value = "/getLogList")
	public String getLogList(Long orderId) {
		WebUtil.getRequest().setAttribute("orderId", orderId);
		return "admin/lin/LinOrderLog-list";
	}
	/**
	 * 按月份统计订单
	 */
	@RequestMapping(value = "/getOrderStatistics")
	public @ResponseBody AjaxResult getOrderMonth(LinOrder linOrder, PaginationVO pageVo) {
		matrixAdapter.isBtnPermitted(search);
		
		String login_plat = String.valueOf(WebUtil.getSessionAttribute(SystemConstance.LOGIN_PLAT));
		if(SystemConstance.PLAT_HOTEL.equals(login_plat)) {
			SysUsers loginUser = matrixAdapter.getLoginUser();
			loginUser = sysUsersService.findById(loginUser.getSuId());
			
			if(loginUser.getSuDeptId() == null) {
				return new AjaxResult(AjaxResult.STATUS_OK, new ArrayList<>());
			}
			linOrder.setHotelId(loginUser.getSuDeptId());
		}
		List<LinOrder> orderList=linOrderService.findTotalByMonth(linOrder, pageVo);
		AjaxResult result = new AjaxResult(AjaxResult.STATUS_OK, null, null, orderList, linOrderService.findRecordByMonth(linOrder));
		return result;
	}
	/**
	 * 进入按月份查询订单界面
	 */
	@RequestMapping(value = "/getStatisticsDetail")
	public String getStatisticsDetail(String month, Long hotelId, String orderType) {
		WebUtil.getRequest().setAttribute("month", month);
		WebUtil.getRequest().setAttribute("hotelId", hotelId);
		WebUtil.getRequest().setAttribute("orderType", orderType);
		return "admin/lin/LinOrderStatistics-detail";
	}
	/**
	 * 查询订单信息中所有月份
	 */
	@RequestMapping(value = "/getMonth")
	public @ResponseBody AjaxResult getMonth(LinOrder linOrder) {
		matrixAdapter.isBtnPermitted(search);
		List<LinOrder> orderList=linOrderService.findTotalByMonth(linOrder, null);
		AjaxResult result = new AjaxResult(AjaxResult.STATUS_OK, null, null, orderList,null);
		return result;
	}
	
	/**
	 * 导出订单统计详情
	 */
	@RequestMapping(value="/ExporOrderDetail")
	public @ResponseBody ModelAndView Exportthsc(ModelMap model, HttpServletRequest request, HttpServletResponse response,LinOrder linOrder) throws Exception {
		
	    List<LinOrder> dataList=linOrderService.findInPage(linOrder,null);
	    List< List< Object > > list = new ArrayList< >();
	    	for (LinOrder obj : dataList) {
	            List< Object > temp = new ArrayList< >();	         
	            temp.add(obj.getOrderNum());
	            temp.add(obj.getHotelName());
	            if(obj.getOrderState().equals("1")){
	            	temp.add("已创建");
	            }if(obj.getOrderState().equals("2")){
	            	temp.add("入库运输");
	            }if(obj.getOrderState().equals("3")){
	            	temp.add("已入库");
	            }if(obj.getOrderState().equals("4")){
	            	temp.add("已出库");
	            }if(obj.getOrderState().equals("5")){
	            	temp.add("出库运输");
	            }if(obj.getOrderState().equals("6")){
	            	temp.add("已验收");
	            }
	           
	            temp.add(obj.getOrderTotalNum());
	            temp.add(obj.getOrderTotalPrice());
	            temp.add(obj.getOrderTotalLoss());
	            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	            String dateString = formatter.format(obj.getOrderCreatetime());
	            temp.add(dateString);
	            temp.add(obj.getOrderRemark());
	          /*  
	            List<LinOrderDetails> dataList2 = linOrderDetailsService.getOrderDetails(obj.getOrderId(), null);
	            List<Object> detail=new ArrayList<>();
	            for(LinOrderDetails d:dataList2){
	            	detail.add(d.getTypeName());
	            	detail.add(d.getDetailsNum());
	            	detail.add(d.getTypeUnit());
	            	detail.add(d.getTypePrice());
	             }
	            temp.add(detail);*/
	            list.add(temp);
	            
	        }
	     //调用我们的excel工具类，导出数据
	    HSSFWorkbook workbook = ExcelUtil.generateExcel("订单统计详情列表",
	            new String[]{ "订单编号","酒店名","订单状态 ","总数量 ","总价格 ", "总耗损"," 创建时间","订单备注 ","布草种类","布草名称","数量","单位","单价  "}
	            , list);
	    
	         
	    try {
	        ViewExcel.buildExcel(null, workbook, request, response, "订单统计详情列表.xls");
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return new ModelAndView(new ViewExcel(), model);
	}
	
	/**
	 * 导出企业信息列表
	 */
	@RequestMapping("/exporOrderDetail")
	public void exporOrderDetail(LinOrder linOrder, String orderType, PaginationVO pageVo, HttpServletResponse response) {
		
		String login_plat = String.valueOf(WebUtil.getSessionAttribute(SystemConstance.LOGIN_PLAT));
		if(SystemConstance.PLAT_HOTEL.equals(login_plat)) {
			SysUsers loginUser = matrixAdapter.getLoginUser();
			loginUser = sysUsersService.findById(loginUser.getSuId());
			
			if(loginUser.getSuDeptId() == null) {
				throw new GlobleException("导出失败，请刷新重试！");
			}
			linOrder.setHotelId(loginUser.getSuDeptId());
		}
		if (pageVo == null) {
			pageVo = new PaginationVO();
		}
		pageVo.setOrder("DESC");
		pageVo.setSort("order_createtime");
		
		List<LinOrder> dataList = linOrderService.findInPage(linOrder,pageVo);
		
		// 导出订单统计信息
		String[] titles = { "订单编号","酒店名","订单状态 ","总数量 ","总价格 ", "总耗损"," 创建时间","订单备注 " };
		XSSFWorkbook workbook = new XSSFWorkbook();
		XSSFSheet sheet = workbook.createSheet("订单统计信息");
		// 产生表格标题行
		XSSFRow row = sheet.createRow(0);
		// 标题样式
		XSSFCellStyle style = workbook.createCellStyle();
		style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); // 垂直居中
//		style.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 水平居中
		XSSFFont font = workbook.createFont();
		font.setColor(XSSFFont.DEFAULT_FONT_COLOR); // 字体颜色
		font.setFontHeightInPoints((short) 12); // 字体大小
		font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD); // 字体增粗
		style.setFont(font);

		for (int i = 0; i < titles.length; i++) {
			XSSFCell cell = row.createCell(i);
			cell.setCellValue(titles[i]);
			cell.setCellStyle(style);
		}
		sheet.setColumnWidth(0, 15 * 256); // 设置列宽，30个字符宽
		sheet.setColumnWidth(1, 30 * 256);
		sheet.setColumnWidth(2, 15 * 256);
		sheet.setColumnWidth(3, 15 * 256);
		sheet.setColumnWidth(4, 20 * 256);
		sheet.setColumnWidth(5, 15 * 256);
		sheet.setColumnWidth(6, 30 * 256);
		sheet.setColumnWidth(7, 60 * 256);
		
		for (int i = 0; i < dataList.size(); i++) {
			LinOrder data = dataList.get(i);
			
			Double totalPrice = new Double(0);
			
			if(SystemConstance.PLAT_FACTORY.equals(login_plat)) {
				totalPrice = data.getOrderTotalPrice();
			} else if(SystemConstance.PLAT_COMPANY.equals(login_plat)) {
				totalPrice = "factory".equals(orderType) ? data.getOrderTotalPrice() : data.getOrderRealPrice();
			} else {
				totalPrice = data.getOrderRealPrice();
			}

			XSSFRow dataRow = sheet.createRow(i + 1);
			dataRow.createCell(0).setCellValue(data.getOrderNum());
			dataRow.createCell(1).setCellValue(data.getHotelName());
			dataRow.createCell(2).setCellValue(fmtOrderState(data.getOrderState()));
			dataRow.createCell(3).setCellValue(data.getOrderTotalNum().toString());
			dataRow.createCell(4).setCellValue(fmtPrice(totalPrice));
			dataRow.createCell(5).setCellValue(data.getOrderTotalLoss() != null ? data.getOrderTotalLoss().toString() : "0");
			dataRow.createCell(6).setCellValue(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(data.getOrderCreatetime()));
			dataRow.createCell(7).setCellValue(data.getOrderRemark());
		}
		
		OutputStream ouputStream = null;
		try {
			response.setContentType("application/x-download");// 设置response内容的类型
			response.setHeader("Content-disposition", "attachment;filename="
					+ URLEncoder.encode("订单统计信息.xlsx", "UTF-8"));// 设置头部信息
			ouputStream = response.getOutputStream();
			workbook.write(ouputStream);
			ouputStream.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				ouputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
		
	private String fmtOrderState(String orderState) {
		switch(orderState) {
		case SystemConstance.ORDER_STATE_CREATE : return "已创建";
		case SystemConstance.ORDER_STATE_TRANSPORT1 : return "入库运输";
		case SystemConstance.ORDER_STATE_STORAGE : return "已入库";
		case SystemConstance.ORDER_STATE_OUT : return "已出库";
		case SystemConstance.ORDER_STATE_TRANSPORT2 : return "出库运输";
		case SystemConstance.ORDER_STATE_INSPECTED: return "已验收";
		default: return "";
		}
	}
	
	private String fmtPrice(Double price) {
		return price != null ? new java.text.DecimalFormat("0.00").format(price) : "";
	}
	
}